<?php

class DB {
    private static $instance = null;
    private $connection = null;
    private $result = null;

    private function __construct(){ 
        $this->connect(); 
    }
    
    public static function getInstance(){
        if(!isset(DB::$instance)){
            self::$instance = new DB();
        }
        if(!is_resource(self::$instance->connection)){
            self::$instance->connect();
        }
        return self::$instance; 
    }
    
    private function connect(){
        $con_string = "host=" . POSTGRES_SERVER;
        $con_string .= " port=" . POSTGRES_PORT;
        $con_string .= " dbname=" . POSTGRES_DB;
        $con_string .= " user=" . POSTGRES_USER;
        $con_string .= " password=" . POSTGRES_PASSWORD;
        $this->connection = pg_connect($con_string);
    }
    
    public function close(){
        if(is_resource($this->connection))
            pg_close($this->connection);
    }
    
    public function execute($sql){
        $this->result = pg_query($sql);
    }
    
    public function fetchAll(){
        $return = array();
        while($row = pg_fetch_array($this->result, null, PGSQL_ASSOC)){
            $return[] = $row;
        }
        return $return;
    }
    
    public function numRows(){
        return pg_num_rows($this->result);
    }
    
    public function affectedRows(){
        return pg_affected_rows($this->result);
    }
    
    public function escape($text){
        return pg_escape_string($text);
    }
    
    public function lastError(){
        return pg_last_error($this->connection);
    }
}

?>
